package init.luoyu.easymonitor.base.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.extension.service.IService;
import com.google.common.collect.Lists;
import init.luoyu.easymonitor.base.model.ServiceResult;
import init.luoyu.easymonitor.base.model.input.CreateInput;
import init.luoyu.easymonitor.base.model.input.UpdateInput;
import init.luoyu.easymonitor.base.service.IBaseService;
import init.luoyu.easymonitor.base.utils.CommonUtil;
import init.luoyu.easymonitor.generator.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author LuoYu
 * date 2021/4/13
 */
@Slf4j
public class BaseServiceImpl<T extends Model<T>,Mapper extends BaseMapper<T>,Create extends CreateInput,Update extends UpdateInput> implements IBaseService<T,Mapper,Create,Update> {


    private  String MODULE = "基础模块";

    /**
     * Mapper
     */
    private Mapper mapper;

    /**
     * Service
     */
    private IService<T> service;


    /**
     * 实体类型
     */
    private Class<T> tClass;





    public BaseServiceImpl(Mapper mapper, IService<T> service,Class<T> tClass,String model) {
        this.mapper = mapper;
        this.service = service;
        this.tClass = tClass;
        this.MODULE = model;

    }

    @Override
    public ServiceResult<Long> save(Create create) {
        log.info("创建"+MODULE);
        long id = IdWorker.getId();
        create.setId(id);
        ModelMapper modelMapper = getModelMapper();
        T t = modelMapper.map(create, this.tClass);
        boolean save = service.save(t);
        if(!save) {
            log.error("创建{}失败....",MODULE);
            return ServiceResult.error("创建失败");
        }
        return new ServiceResult<>(id);
    }

    @Override
    public ServiceResult<Boolean> bulkSave(List<Create> list) {
        log.info("批量保存 ----> 模块:{}",MODULE);
        if(CommonUtil.isEmptyCollection(list)) {
            return ServiceResult.error("列表不能为空");
        }
        List<Long> ids = IdWorker.getIds(list.size());
        ModelMapper modelMapper = getModelMapper();
        List<T> tList = Lists.newArrayList();
        for(int i=0;i<ids.size();i++) {
            Create create = list.get(i);
            create.setId(ids.get(i));
            T entity = modelMapper.map(create, tClass);
            tList.add(entity);
        }
        boolean saveBatch = this.getService().saveBatch(tList);
        if(!saveBatch) {
            return ServiceResult.error("批量保存失败");
        }
        return ServiceResult.success(true);
    }

    @Override
    public ServiceResult<T> get(Long id) {
        T t = mapper.selectById(id);
        return ServiceResult.success(t);
    }

    @Override
    public T getById(Long id, String... fields) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        if(fields != null && fields.length > 0) {
            queryWrapper.select(fields);
        }
        queryWrapper.eq("id",id);
        return mapper.selectOne(queryWrapper);
    }

    @Override
    public ServiceResult<Boolean> delete(Long id) {
        log.info("删除实体 ----> 模块:{} -- id:{}", MODULE,id);
        if (!hasExist(id)) {
            log.warn("实体不存在无法删除 ----> 模块:{} -- id:{}",MODULE,id);
            return ServiceResult.error(MODULE.concat("不存在"));
        }
        UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("isDeleted", true);
        updateWrapper.set("deleteTime", LocalDateTime.now());
        updateWrapper.eq("id", id);
        boolean update = service.update(updateWrapper);
        if(!update) {
            log.error("删除失败 ----> 模块:{} -- id:{}",MODULE,id);
            return ServiceResult.error("删除失败");
        }
        return ServiceResult.success(true);
    }

    @Override
    public ServiceResult<Boolean> update(Update update) {
        log.info("更新实体 ----> 模块:{} -- id：{}",MODULE,update.getId());
        update.setUpdateTime(LocalDateTime.now());
        ModelMapper mapper = getModelMapper();
        T entity = mapper.map(update, tClass);
        boolean saveOrUpdate = service.saveOrUpdate(entity);
        if(!saveOrUpdate) {
            log.warn("更新实体失败 ----> 模块:{} -- id:{}",MODULE,update.getId());
            return ServiceResult.error("更新失败");
        }
        return ServiceResult.success(true);
    }

    @Override
    public ServiceResult<List<T>> list(QueryWrapper<T> queryWrapper) {
        return null;
    }

    @Override
    public boolean hasExist(Long id) {
        T t = service.getById(id);
        return t != null;
    }

    @Override
    public Mapper getMapper() {
        return this.mapper;
    }

    @Override
    public IService<T> getService() {
        return this.service;
    }

    private ModelMapper getModelMapper(){
        return new ModelMapper();
    }


}
